<?php

// +---------------------------------------------------------------
// | Name: 星空框架 会员管理
// +---------------------------------------------------------------
// | Version: V5.0
// +---------------------------------------------------------------
// | Author: xkyinzhe <zhonghuaxinxing@sina.cn>
// +---------------------------------------------------------------
// | Time: 2021-05-07 17:20
// +---------------------------------------------------------------
declare(strict_types=1);

namespace app\api\controller\v1;

use app\common\common\IndexController;
use app\common\model\Address as AddressModel;
use app\common\model\Area as AreaModel;
use app\common\model\BackMoney as BackMoneyModel;
use app\common\model\User as UserModel;
use app\common\model\Order as OrderModel;
use app\common\model\SubOrder as SubOrderModel;
use app\common\model\RefundOrder as RefundOrderModel;
use app\common\model\Poster as PosterModel;
use app\common\model\PushMsg as PushMsgModel;
use app\common\model\UserAchievement as UserAchievementModel;
use app\common\model\HistorySearch as HistorySearchModel;
use app\common\model\MoneyChanage as MoneyChanageModel;
use app\common\model\Withdrawal as WithdrawalModel;
use app\common\model\GoodsOrder as GoodsOrderModel;
use app\common\model\Finance as FinanceModel;
use app\common\controller\Huigongbao;
use app\common\services\UserServices;
use app\common\services\OSS;
use app\common\services\Lock;
use think\facade\Db;

/**
 * @xk 会员管理
 */
class User extends IndexController
{
    // +------------
    // | 地址处理
    // +-----------------

    /**
     * @xk 省市区列表
     *
     * @method getArea
     *
     * @param AreaModel $areaModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-10T15:19:45+080
     */
    public function getArea(AreaModel $areaModel)
    {
        $param = request()->param();
        $p_code = isset($param['p_code']) ? $param['p_code'] : '100000';
        $condition = [];
        $condition[] = ['p_code', '=', $p_code];
        // $condition[] = ['status', '=', 1];
        $code = 200;
        $msg = '请求成功';
        $list = $areaModel
              ->where($condition)
              ->field('`name`,`code`,`center`,`cn_name`,`first_name`,`level`')
              ->select();
        $result_count = $areaModel->where($condition)->count();
        $result_code = 200;
        $result_msg = '加载成功';
        $resultData = [];
        $resultData['list'] = $list;
        $this->result($code, $msg, $result_code, $result_msg, $resultData, $result_count);
    }

    /**
     * @xk 用户地址列表
     *
     * @method addressList
     *
     * @param AddressModel $addressModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-10T15:10:13+080
     */
    public function addressList(AddressModel $addressModel)
    {
        $param = request()->param();
        $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
        $code = 200;
        $msg = '请求成功';
        if (!$user_sn) {
            $result_code = 404;
            $result_msg = '您还没有登录，请先进行登录';
            $this->result($code, $msg, $result_code, $result_msg);
        }
        $condition = [];
        $condition[] = ['a.user_sn', '=', $user_sn];
        $list = $addressModel
              ->alias('a')
              ->where($condition)
              ->field('`address_id`,`name`,`tel`,`user_sn`,`province`,`city`,`area`,`street`,`address`,`is_default`')
              ->order(['is_default desc','create_time desc'])
              ->select()
              ->toArray();
        $result_count = $addressModel->alias('a')->where($condition)->count();
        $result_code = 200;
        $result_msg = '加载成功';
        $resultData = [];
        $resultData['list'] = $list;
        $this->result($code, $msg, $result_code, $result_msg, $resultData, $result_count);
    }

    /**
     * @xk 用户地址保存
     *
     * @method addressSave
     *
     * @param AddressModel $addressModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-10T15:10:42+080
     */
    public function addressSave(AddressModel $addressModel, UserModel $userModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $act = isset($param['act']) ? $param['act'] : 'create';
            $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            $param['is_default'] = isset($param['is_default']) ? $param['is_default'] : 0;
            if ($param['is_default'] > 0) {
                $addressModel->where([['user_sn', '=', $param['user_sn']]])->save(['is_default' => 0]);
            }
            $user_info = $userModel->where([['user_sn', '=', $param['user_sn']]])->field('`status`,`is_bind`,`tel`')->find();
            if (!$user_info) {
                throw new \think\Exception('请先登录', 404);
            }
            if (1 != $user_info['status']) {
                throw new \think\Exception('账户已注销', 404);
            }
            $addressModel->validate($param, $act);
            switch ($act) {
            case 'create':
              unset($param['address_id']);
              $res = $addressModel->create($param);
              $resultData['address_id'] = $res->address_id;
              break;
            case 'edit':
              $res = $addressModel->find($param['address_id'])->save($param);
              $resultData['address_id'] = $param['address_id'];
              break;
            case 'chanageDefault':
              $res = $addressModel->where([['user_sn','=',$user_sn]])->save(['is_default'=>0]);
              $res = $addressModel->find($param['address_id'])->save($param);
              $resultData['address_id'] = $param['address_id'];
              break;
          }
            Db::commit();
            $result_msg = '地址更新成功';
            $result_code = 200;
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }

    /**
     * @xk 获取地址详细信息
     *
     * @method addressInfo
     *
     * @param AddressModel $addressModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-10T15:47:41+080
     */
    public function addressInfo(AddressModel $addressModel)
    {
        $param = request()->param();
        $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
        $address_id = isset($param['address_id']) ? $param['address_id'] : 0;
        $code = 200;
        $msg = '请求成功';
        if ('' == $user_sn) {
            $result_code = 404;
            $result_msg = '您还没有登录，请先登录';
            $this->result($code, $msg, $result_code, $result_msg);
        }
        if ($address_id <= 0) {
            $result_code = 404;
            $result_msg = '请选择需要编辑的地址';
            $this->result($code, $msg, $result_code, $result_msg);
        }
        $result_code = 200;
        $result_msg = '加载成功';
        $resultData = [];
        $resultData['info'] = $addressModel
      ->field('`address_id`,`name`,`tel`,`user_sn`,`province`,`province_code`,`city`,`city_code`,`area`,`area_code`,`street`,`street_code`,`address`,`is_default`,`center`')
      ->find($address_id);
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }

    /**
     * @xk 地址删除
     *
     * @method addressDelete
     *
     * @param AddressModel $addressModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-10T16:15:32+080
     */
    public function addressDelete(AddressModel $addressModel, UserModel $userModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            $user_info = $userModel->where([['user_sn', '=', $user_sn]])->field('`status`,`is_bind`,`tel`')->find();
            if (!$user_info) {
                throw new \think\Exception('请先登录', 404);
            }
            if (1 != $user_info['status']) {
                throw new \think\Exception('账户已注销', 404);
            }
            $addressModel->validate($param, 'delete');
            $res = $addressModel->destroy($param['address_id']);
            $result_code = 200;
            $result_msg = '地址删除成功';
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }

    /**
     * @xk 校验验证码
     *
     * @method checkMsgCode
     *
     * @param UserModel $userModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-12T15:36:29+080
     */
    public function checkMsgCode(UserModel $userModel)
    {
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $act = isset($param['act']) ? $param['act'] : 'chanagetel';
            $userModel->validate($param, $act);
            $check_captch_result = $userModel->checkCaptch($param['tel'], $act, $param['captch']);
            if (!$check_captch_result) {
                throw new \think\Exception('验证码已经过期或失效，请重新获取验证', 404);
            }
            $result_code = 200;
            $result_msg = '验证成功';
        } catch (\Exception $e) {
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }

    // +----------------
    // | 修改个人资料
    // +------------------

    /**
     * @xk 修改头像
     *
     * @method chanageAvatar
     *
     * @param UserModel $userModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-12T16:10:22+080
     */
    public function chanageAvatar(UserModel $userModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $userModel->validate($param, 'chanageAvatar');
            $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            $param['head_pic'] = str_replace("\/", '/', str_replace('"', '', $param['head_pic']));
            $user_info = $userModel->where([['user_sn', '=', $user_sn]])->field('`status`,`is_bind`,`tel`')->find();
            if (!$user_info) {
                throw new \think\Exception('请先登录', 404);
            }
            if (1 != $user_info['status']) {
                throw new \think\Exception('账户已注销', 404);
            }
            $res = $userModel->where([['user_sn', '=', $user_sn]])->find()->save(['head_pic' => $param['head_pic']]);
            Db::commit();
            $result_code = 200;
            $result_msg = '修改成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }
    /**
     * @xk 修改保存
     *
     * @method chanageSave
     * @param  UserModel   $userModel                 [description]
     * @return [type]      [description]
     * @Time   2021-09-09
     * @City   青岛
     * @Author xkyinzhe    <zhonghuaxinxing@sina.cn>
     */
    public function chanageSave(UserModel $userModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $userModel->validate($param, 'chanageNickname');
            $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            $user_info = $userModel->where([['user_sn', '=', $user_sn]])->field('`status`,`is_bind`,`tel`')->find();
            if (!$user_info) {
                throw new \think\Exception('请先登录', 404);
            }
            if (1 != $user_info['status']) {
                throw new \think\Exception('账户已注销', 404);
            }
            $res = $userModel->where([['user_sn', '=', $user_sn]])->find()->save($param);
            Db::commit();
            $result_code = 200;
            $result_msg = '修改成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }

    /**
     * @xk 修改昵称
     *
     * @method chanageNickname
     *
     * @param UserModel $userModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-12T16:10:12+080
     */
    public function chanageNickname(UserModel $userModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $userModel->validate($param, 'chanageNickname');
            $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            $user_info = $userModel->where([['user_sn', '=', $user_sn]])->field('`status`,`is_bind`,`tel`')->find();
            if (!$user_info) {
                throw new \think\Exception('请先登录', 404);
            }
            if (1 != $user_info['status']) {
                throw new \think\Exception('账户已注销', 404);
            }
            $res = $userModel->where([['user_sn', '=', $user_sn]])->find()->save(['user_name' => preg_replace('/[\xf0-\xf7].{3}/', '', $param['user_name'])]);
            Db::commit();
            $result_code = 200;
            $result_msg = '修改成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }
    // +---------------------
    // | 获取用户信息
    // +---------------------------

    /**
     * @xk 获取用户信息
     *
     * @method getUserInfo
     *
     * @param UserModel $userModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-14T14:43:18+080
     */
    public function getUserInfo(UserModel $userModel, SubOrderModel $subOrderModel, Huigongbao $huigongbao, RefundOrderModel $refundOrderModel, BackMoneyModel $backMoneyModel, OrderModel $orderModel,PushMsgModel $pushMsgModel)
    {
        $param = request()->param();
        $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        if ($user_sn == '') {
            $result_code = 404;
            $result_msg = '您还没有登录，请先登录！';
            $this->result($code, $msg, $result_code, $result_msg);
        }
        $user_info = $userModel
                   ->alias('u')
                   ->leftJoin('userLevel ul', 'ul.level=u.level')
                   ->leftJoin('user uu', 'uu.user_sn=u.l_user_sn')
                   ->where([['u.user_sn', '=', $user_sn]])
                   ->field('u.`user_sn`,u.`level`,u.`user_name`,u.`head_pic`,u.`tel`,u.`is_bind`,u.`head_pic` as head_pic_show,u.`back_money`,u.`all_back_money`,ul.`level_name`,u.`status`,u.`create_time`,u.`l_user_sn`,uu.user_name as l_user_name,u.`is_buy`,u.`purchases_order_price`,u.`is_check`,u.`card_num`,u.`level`')
                   ->withAttr('head_pic_show', function ($value, $data) {
                       return getShowUrl($value);
                   })
                   ->withAttr('l_user_sn', function ($value, $data) {
                       return $value>0 ? $value : '';
                   })
                   ->withAttr('l_user_name', function ($value, $data) {
                       if ($data['l_user_sn'] > 0) {
                           return $value.'('.$data['l_user_sn'].')';
                       } else {
                           return '';
                       }
                   })
                   ->find();
        if (!$user_info) {
            $result_code = 404;
            $result_msg = '用户信息不存在，请检查！';
            $this->result($code, $msg, $result_code, $result_msg);
        }
        $user_info->toArray();
        if (1 != $user_info['status']) {
            $result_code = 404;
            $result_msg = '账户已注销';
            $this->result($code, $msg, $result_code, $result_msg);
        }
        if ($user_info['is_check'] == 0) {
            $hg_appid = config('core_config.huigongbao_new_config.hg_appid');
            $callBackUrl = urlencode('https://'.$_SERVER['HTTP_HOST'].'/#/pages/administration/administration');
            $checkUrl = config('core_config.huigongbao_new_config.hg_jumpurl').'appId='.$hg_appid.'&callBackUrl='.$callBackUrl.'&remark='.$user_sn;
            $user_info['checkUrl'] = $checkUrl;
        }
        // if ($user_info['is_check'] == 0) {
        //     $token = $huigongbao->getToken();
        //     $notifyUrl = urlencode('https://'.$_SERVER['HTTP_HOST'].'/common/huigongbao/createBack');
        //     $callBackUrl = urlencode('https://'.$_SERVER['HTTP_HOST'].'/#/pages/administration/administration');
        //     $checkUrl = config('core_config.huigongbao_new_config.hg_jumpurl').'&token='.$token.'&notifyUrl='.$notifyUrl.'&callBackUrl='.$callBackUrl.'&callBackParam='.$user_sn;
        //     $user_info['checkUrl'] = $checkUrl;
        // }
        $condition = [];
        $condition[] = ['user_sn','=',$user_sn];
        $resultData['order_count'] = [
          'wait_pay_count' => $orderModel->where($condition)->where([['status','=',0]])->count(),
          'wait_shipping_count' => $subOrderModel->where($condition)->where([['status','in','1,2'],['shipping_type','<>',2],['refund_status', '<>', '2']])->count(),
          'wait_sure_count' => $subOrderModel->where($condition)->where([['status','=','2'],['shipping_type','=',2],['refund_status', '<>', '2']])->count(),
          'refund_count' => $refundOrderModel->where($condition)->where([['status', 'not in', '1.3,2.5,2.2,1.2,3.2,3.4']])->count()
        ];
        // $all_price = $backMoneyModel->where([['user_sn','=',$user_sn],['act','=',1],['is_finance','=',1]])->sum('achievement_price');
        // $all_refund_price = $backMoneyModel->where([['user_sn','=',$user_sn],['act','=',11],['is_finance','=',1]])->sum('achievement_price');
        // $user_info['user_order_price'] = sprintf('%.2f',((float)$all_price-(float)$all_refund_price));

        $user_order_price = $backMoneyModel
        ->alias('bc')
        ->leftJoin('goodsOrder go','go.sub_order_sn=bc.sub_order_sn and status = 3.1')
        ->where([['bc.user_sn','=',$user_sn],['bc.act','=',1],['bc.is_finance','=',1]])->group("bc.`sub_order_sn`")->sum('go.sub_total');
        // 此处不使用业绩来进行统计 改为使用订单

        $user_info['user_order_price'] = $user_order_price;
        $user_info['push_count'] = $pushMsgModel
                                  ->where([['user_sn','=',$user_sn],['is_read','=',0]])
                                  ->count();
        $user_info['child_count'] = $userModel->where([['l_user_sn','=',$user_sn]])->count();
        $resultData['kf_picurl'] = getShowUrl(config('web_config.kf_picurl'));
        $resultData['wx_ewm'] = getShowUrl(config('web_config.wx_ewm'));
        $result_code = 200;
        $result_msg = '加载成功';
        $resultData['info'] = $user_info;
        $resultData['Qrcode']=config("web_config.user_index_qrcode");
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 获取余额转增信息
     * @method                                 getChanageUserInfo
     * @param                                  UserModel $userModel  [description]
     * @return                                 [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                        <zhonghuaxinxing@sina.cn>
     * @City：青岛
     * @Time：2022-06-14T09:false54:false19+080
     */
    public function getChanageUserInfo(UserModel $userModel)
    {
        $param = request()->param();
        $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
        $get_user_sn = isset($param['get_user_sn']) ? $param['get_user_sn'] : '';
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        if ($user_sn == '') {
            $result_code = 404;
            $result_msg = '您还没有登录，请先登录！';
            $this->result($code, $msg, $result_code, $result_msg);
        }
        $user_info = $userModel
                   ->alias('u')
                   ->where([['u.user_sn', '=', $get_user_sn]])
                   ->field('u.`user_sn`,u.`level`,u.`user_name`,u.`status`')
                   ->find();
        if (!$user_info) {
            $result_code = 404;
            $result_msg = '用户信息不存在，请检查！';
            $this->result($code, $msg, $result_code, $result_msg);
        }
        $user_info->toArray();
        if (1 != $user_info['status']) {
            $result_code = 404;
            $result_msg = '接收会员账户已注销';
            $this->result($code, $msg, $result_code, $result_msg);
        }
        $result_code = 200;
        $result_msg = '加载成功';
        $resultData['info'] = $user_info;
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 换绑手机号
     *
     * @method el
     * @param  UserModel               $userModel                [description]
     * @return [type]                                            [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-06-03T14:16:27+080
     */
    public function chanageTel(UserModel $userModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $userModel->validate($param, 'chanagetel');
            $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            $act = 'chanagetel';
            $user_info = $userModel->where([['user_sn', '=', $user_sn]])->field('`status`,`is_bind`,`tel`')->find();
            if (!$user_info) {
                throw new \think\Exception('请先登录', 404);
            }
            if (1 != $user_info['status']) {
                throw new \think\Exception('账户已注销', 404);
            }
            $check_captch_result = $userModel->checkCaptch($param['tel'], $act, $param['captch']);
            if (!$check_captch_result) {
                throw new \think\Exception('验证码已经过期或失效，请重新获取验证', 404);
            }
            $check_mobile_result = $userModel->checkMobile($param['tel'], $act);
            if (!$check_mobile_result) {
                throw new \think\Exception('当前手机号已经绑定其他账号，请更换手机号', 404);
            }
            $res = $userModel->where([['user_sn', '=', $user_sn]])->find()->save(['tel' => $param['tel']]);
            Db::commit();
            $result_code = 200;
            $result_msg = '绑定手机号修改成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }

    // +----------------
    // | 申请提现
    // +-------------------
    /**
     * @xk 申请提现
     *
     * @method withdrawalSave
     * @param  SecondWithdrawalModel $secondWithdrawalModel     [description]
     * @param  UserModel             $userModel                 [description]
     * @return [type]                [description]
     * @Time   2021-09-22
     * @City   青岛
     * @Author xkyinzhe              <zhonghuaxinxing@sina.cn>
     */
    public function withdrawalSave(WithdrawalModel $withdrawalModel, UserModel $userModel)
    {
        Db::startTrans();
        $param = request()->param();
        $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
        $lock = (new Lock())->lock([$param['user_sn']], 3000);
        $code = 200;
        $msg = '请求成功';
        try {
            $money = isset($param['money']) ? $param['money'] : 0.00;
            $min_money = config('web_config.min_withdrawl_money');
            if (!$lock) {
                throw new \think\Exception("操作频繁，请稍后", 404);
            }
            $user_info = $userModel->where([['user_sn', '=', $user_sn]])->field('`status`,`is_bind`,`back_money`,`card_num`,`is_check`')->find();
            if (!$user_info) {
                throw new \think\Exception('请先登录', 404);
            }
            if (1 != $user_info['status']) {
                throw new \think\Exception('账户已注销', 404);
            }
            if (1 != $user_info['is_check']) {
                throw new \think\Exception('请先完成实名认证', 404);
            }
            if ($money < $min_money) {
                throw new \think\Exception("提现金额不能小于".$min_money, 404);
            }
            if ($money > $user_info['back_money']) {
                throw new \think\Exception("提现金额大于拥有金额，无法完成", 404);
            }
            // 开始执行提现记录写入
            $with_drawal_data = [];
            $with_drawal_data['user_sn'] = $user_sn; // 用户编号
            $with_drawal_data['money'] = $money; // 提现金额
            $with_drawal_data['card_num'] = $user_info['card_num']; // 身份证号码
            $with_drawal_data['bank_num'] = $param['bank_num']; // 身份证号码
            $with_drawal_data['name'] = $param['name']; // 身份证号码
            $with_drawal_data['bank_name'] = $param['bank_name']; // 身份证号码
            // $with_drawal_data['bank_num'] = $param['bank_num']; // 身份证号码
            $withdrawalModel->create($with_drawal_data);
            $userModel->where([['user_sn', '=', $user_sn]])->dec('back_money', (float)$money)->update();
            $userModel->where([['user_sn', '=', $user_sn]])->inc('frozen_money', (float)$money)->update();
            $result_code = 200;
            $result_msg = '提交成功，请等待审核。遇到节假日，提现审核会顺延至节后哦。';
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }
    /**
     * @xk 获取提现记录
     *
     * @method getWithdrawalList
     * @param  SecondWithdrawalModel $secondWithdrawalModel     [description]
     * @return [type]                [description]
     * @Time   2021-09-22
     * @City   青岛
     * @Author xkyinzhe              <zhonghuaxinxing@sina.cn>
     */
    public function getWithdrawalList(WithdrawalModel $withdrawalModel, UserModel $userModel, FinanceModel $financeModel)
    {
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            $page = isset($param['page']) ? (int)$param['page'] : 1;
            $limit = isset($param['limit']) ? (int)$param['limit'] : 30;
            $type = isset($param['type']) ? $param['type'] : 1;
            $condition = [];
            $user_info = $userModel
             ->alias('u')
             ->where([['u.user_sn', '=', $user_sn]])
             ->field('u.`tel`,u.`is_bind`,u.`status`,u.`back_money`')
             ->find();
            if (!$user_info) {
                $result_code = 404;
                $result_msg = '用户信息不存在，请先登录！';
                $this->result($code, $msg, $result_code, $result_msg);
            }
            if (1 != $user_info['status']) {
                $result_code = 404;
                $result_msg = '账户已注销';
                $this->result($code, $msg, $result_code, $result_msg);
            }
            $condition = [];
            switch ($type) {
              case '1':
                $condition[] = ['user_sn', '=', $user_sn];
                $result_count = $withdrawalModel
                            ->alias('u')
                            ->where($condition)
                            ->count();
                if ($result_count <= ($page-1)*$limit) {
                    $resultData['list'] = [];
                    $resultData['page'] = $page;
                    throw new \think\Exception("没有更多数据了", 203);
                    exit();
                }
                $list = $withdrawalModel
                  ->where($condition)
                  ->field('`with_drawal_id`,`withdrawal_sn`,`money`,`status`,`status` as status_show,`create_time` as show_time,`create_time` as show_date,bank_num')
                  ->withAttr('status_show', function ($value, $data) {
                      switch ($value) {
                      case '0':
                        return  '等待审核';
                        break;
                      case '1':
                        return '等待审核';
                        break;
                      case '2':
                        return '提现失败';
                        break;
                      case '3':
                        return '提现成功';
                        break;
                      case '4':
                        return '提现失败';
                        break;
                      default:
                        return '未知状态';
                        break;
                    }
                  })
                  ->withAttr('show_date', function ($value, $data) {
                      return chanageDateString($value, 2);
                  })
                  ->withAttr('show_time', function ($value, $data) {
                      return chanageDateString($value, 9);
                  })
                  ->withAttr('bank_num',function($value,$data){
                    return substr_replace($value,'*************',3,9);
                  })
                  ->order('create_time desc')
                  ->page($page, $limit)
                  ->select()
                  ->toArray();
                break;
              case '2':
                $condition[] = ['relation_user_num', '=', $user_sn];
                $condition[] = ['pay_type','=',3];
                $condition[] = ['act','<>',3];
                $result_count = $financeModel
                            ->where($condition)
                            ->count();
                if ($result_count <= ($page-1)*$limit) {
                    $resultData['list'] = [];
                    $resultData['page'] = $page;
                    throw new \think\Exception("没有更多数据了", 203);
                    exit();
                }
                $list = $financeModel
                  ->where($condition)
                  ->field('`finance_id`,`relation_num`,`money`,`entry`,`act` as show_status,`create_time` as show_time,`create_time` as show_date')
                  ->withAttr('show_status', function ($value, $data) {
                      switch ($value) {
                      case '1':
                        return '消费';
                        break;
                      case '2':
                        return '消费';
                        break;
                      case '4':
                        return '退款';
                        break;
                      default:
                        // code...
                        break;
                    }
                  })
                  ->withAttr('money', function ($value, $data) {
                      return $data['entry']==1 ? '-￥'.$value : '￥'.$value;
                  })
                  ->withAttr('show_date', function ($value, $data) {
                      return chanageDateString($value, 2);
                  })
                  ->withAttr('show_time', function ($value, $data) {
                      return chanageDateString($value, 9);
                  })
                  ->order('create_time desc')
                  ->page($page, $limit)
                  ->select()
                  ->toArray();
                break;
            }

            $result_code = 200;
            $result_msg = '加载成功';
            $resultData['list'] = $list;
            $resultData['page'] = $page+1;
        } catch (\Exception $e) {
            $result_code = 404;
            if ($e->getCode() == 203) {
                $result_code = 203;
            }
            $result_msg = $e->getMessage();
            ;
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 我的团队
     *
     * @method myTree
     * @param  UserModel  $userModel                 [description]
     * @return [type]     [description]
     * @Time   2021-09-24
     * @City   青岛
     * @Author xkyinzhe   <zhonghuaxinxing@sina.cn>
     */
    public function getMyTree(UserModel $userModel, UserAchievementModel $userAchievementModel, UserServices $userServices)
    {
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $page = isset($param['page']) ? (int)$param['page'] : 1;
            $limit = isset($param['limit']) ? (int)$param['limit'] : 10;
            $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            if ($user_sn == '') {
                throw new \think\Exception("您还没有登录，请先进行登录", 300);
            }
            $condition = [];
            $condition[] = ['u.l_user_sn','=',$user_sn];
            $condition[] = ['u.level','>=',1]; // 非游客用户
            $result_count = $userModel->alias('u')->where($condition)->count();
            $new_list = [];
            $user_info = $userModel
                          ->alias('u')
                          ->leftJoin('userLevel ul', 'ul.level=u.level')
                          ->where([['u.user_sn','=',$user_sn]])
                          ->field('u.`user_sn`,u.`tel`,u.`user_name`,u.`l_user_sn`,u.`level`,ul.`level_name`,u.`create_time`,ul.`picurl`,u.`all_achievement_price`,`level_1_count`,`level_2_count`,`level_3_count`,`level_4_count`,`level_5_count`')
                          ->withAttr('picurl', function ($value, $data) {
                              return getShowUrl($value);
                          })
                          ->find();
            if($page == 1){
              $new_list[] = $user_info?$user_info->toArray():[];
            }
            if (($result_count <= ($page-1)*$limit) && $page != 1) {
                $resultData['list'] = [];
                $resultData['page'] = $page;
                throw new \think\Exception("没有更多数据了", 404);
            }

            $list = $userModel
                ->alias('u')
                ->leftJoin('userLevel ul', 'ul.level=u.level')
                ->where($condition)
                ->field('u.`user_sn`,u.`tel`,u.`user_name`,u.`l_user_sn`,u.`level`,ul.`level_name`,u.`create_time`,ul.`picurl`,u.`all_achievement_price`,`level_1_count`,`level_2_count`,`level_3_count`,`level_4_count`,`level_5_count`')
                ->withAttr('picurl', function ($value, $data) {
                    return getShowUrl($value);
                })
                ->page($page, $limit)
                ->order(['level desc','all_achievement_price desc','user_sn asc'])
                ->group('u.user_sn')
                ->select()
                ->toArray();
            $list = array_merge($new_list,$list);
            if ($list) {
                foreach ($list as $key => $value) {
                    // 开始获取 会员的相关业绩
                    $now_month = date('Y-m');
                    $condition = [];
                    switch ($value['level']) {
                    case '2':
                      $condition[] = ['create_time','like',$now_month.'%'];
                      $condition[] = ['user_sn','=',$value['user_sn']];
                      // 当月新增总业绩
                      $list[$key]['month_price'] =  sprintf('%.2f',$userAchievementModel->where($condition)->sum('achievement_price'));
                      // 当月团队总业绩
                      $list[$key]['month_team_price'] = sprintf('%.2f',$userAchievementModel->where($condition)->sum('achievement_price'));
                      // 团队总业绩
                      // $list[$key]['all_team_price'] = $userAchievementModel->where([['user_sn','=',$value['user_sn']]])->sum('achievement_price');
                      $list[$key]['all_team_price'] = sprintf('%.2f',$value['all_achievement_price']);
                      // 个人业绩
                      $list[$key]['only_price'] = sprintf('%.2f',$userAchievementModel->where([['create_user_sn','=',$value['user_sn']],['user_sn','=',$value['user_sn']]])->sum('achievement_price'));
                      break;
                    default:
                      $condition[] = ['create_time','like',$now_month.'%'];
                      $only_contion = [];
                      $only_contion = $condition;
                      $condition[] = ['user_sn','=',$value['user_sn']];
                      $only_contion[] = ['user_sn','=',$value['user_sn']];
                      $only_contion[] = ['create_user_sn','=',$value['user_sn']]; // 个人当月
                      // $list[$key]['child_count'] = $userServices->getChildLevel($value['user_sn'], $value['level']);
                      $level = $value['level'];
                      if ($value['level_3_count'] > 0 && $level <= 3) {
                          $list[$key]['child_count'] = 3;
                      }
                      if ($value['level_4_count'] > 0 && $level <= 4) {
                          $list[$key]['child_count'] = 4;
                      }
                      if ($value['level_5_count'] > 0 && $level <= 5) {
                          $list[$key]['child_count'] = 5;
                      }
                       $list[$key]['month_team_price'] = sprintf('%.2f',$userAchievementModel->where($condition)->sum('achievement_price'));
                       $list[$key]['month_only_price'] = sprintf('%.2f',$userAchievementModel->where($only_contion)->sum('achievement_price'));
                       // $list[$key]['all_team_price'] = sprintf('%.2f',0.00);
                       $list[$key]['all_team_price'] = sprintf('%.2f',$value['all_achievement_price']);
                      break;
                  }
                }
            }
            $result_code = 200;
            $result_msg = '加载成功';
            $resultData['list'] = $list;
            $resultData['page'] = $page+1;
            $resultData['all_count'] = $result_count;
        } catch (\Exception $e) {
            $result_code = 404;
            if ($e->getCode() == 203) {
                $result_code = 203;
            }
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 统计上月佣金记录
     *
     * @method getLastMonthPrice
     * @param  UserModel         $userModel                 [description]
     * @param  BackMoneyModel    $backMoneyModel            [description]
     * @return [type]            [description]
     * @Time   2021-10-28
     * @City   青岛
     * @Author xkyinzhe          <zhonghuaxinxing@sina.cn>
     */
    public function getLastMonthPrice(UserModel $userModel, BackMoneyModel $backMoneyModel)
    {
        $param = request()->param();
        $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            // $last_month = date('Y-m', strtotime('-1 month')); // 上月月份
            $last_month = getLastDate('Y-m', 2);
            // $last_month = date('Y-m');
            $condition = [];
            $condition[] = ['user_sn','=',$user_sn]; // 当前会员
            $condition[] = ['is_finance','=',1]; // 已经结算佣金
            $condition[] = ['create_time','like',$last_month.'%'];
            // 广告佣金
            $adv_back_money = $backMoneyModel->where($condition)->where([['act','=',1]])->sum('money');
            $adv_reduce_money = $backMoneyModel->where($condition)->where([['act','=',11]])->sum('money');
            $resultData['adv_back_money'] = sprintf('%.2f',$adv_back_money-$adv_reduce_money);
            // $resultData['adv_back_money'] = sprintf('%.2f',$backMoneyModel->where($condition)->where([['act','=',1]])->sum('money'));
            // 代理+平级
            $agent_back_money = $backMoneyModel->where($condition)->where([['act','=','2']])->sum('money');
            $now_month_condition = [];
            $now_month_condition[] = ['user_sn','=',$user_sn]; // 当前会员
            $now_month_condition[] = ['is_finance','=',1]; // 已经结算佣金
            $now_month = getLastDate('Y-m', 1);
            $now_month_condition[] = ['create_time','like',$now_month.'%'];
            $avt_agent_back_money = $backMoneyModel->where($condition)->where([['act','=','3']])->sum('money');
            $resultData['agent_back_money'] = sprintf('%.2f', ($agent_back_money+$avt_agent_back_money));
            // 铂金分红
            $resultData['bonus_back_money'] = sprintf('%.2f',$backMoneyModel->where($now_month_condition)->where([['act','=',4]])->sum('money'));
            if ($resultData['agent_back_money'] <= 0) {
                $resultData['agent_back_money'] = sprintf('%.2f',0);
            }
            // 其他收益
            $resultData['other_back_money'] = sprintf('%.2f',$backMoneyModel->where($condition)->where([['act','=',10]])->sum('money'));
            $result_code = 200;
            $result_msg = '加载成功';
        } catch (\Exception $e) {
            $result_code = 404;
            if ($e->getCode() == 203) {
                $result_code = 203;
            }
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 获取历史三个月的业绩统计
     *
     * @method getHistoryMoney
     * @param  UserModel       $userModel                 [description]
     * @param  BackMoneyModel  $backMoneyModel            [description]
     * @return [type]          [description]
     * @Time   2021-10-29
     * @City   青岛
     * @Author xkyinzhe        <zhonghuaxinxing@sina.cn>
     */
    public function getHistoryMoney(UserModel $userModel, BackMoneyModel $backMoneyModel)
    {
        $param = request()->param();
        $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            // 'month_name' => getLastDate('m',2)>10?getLastDate('m',2):intval(getLastDate('m',2)),
            $list = [
            [
              'month_name' => getLastDate('m', 2)>10 ? getLastDate('m', 2) : intval(getLastDate('m', 2)),
              'month_value' => getLastDate('Y-m', 2),
              'now_month' => getLastDate('Y-m', 1),
              'ifshow' => true,
            ],
            [
              'month_name' => getLastDate('m', 2, 2)>10 ? getLastDate('m', 2, 2) : intval(getLastDate('m', 2, 2)),
              'month_value' => getLastDate('Y-m', 2, 2),
              'now_month' => getLastDate('Y-m', 2, 1),
              'ifshow' => true,
            ],
            [
              'month_name' => getLastDate('m', 2, 3)>10 ? getLastDate('m', 2, 3) : intval(getLastDate('m', 2, 3)),
              'month_value' => getLastDate('Y-m', 2, 3),
              'now_month' => getLastDate('Y-m', 2, 2),
              'ifshow' => true,
            ],
          ];
            if ($list) {
                foreach ($list as $key => $value) {
                    $condition = [];
                    $condition[] = ['user_sn','=',$user_sn]; // 当前会员
                    $condition[] = ['is_finance','=',1]; // 已经结算佣金
                    $condition[] = ['create_time','like',$value['month_value'].'%'];
                    $now_month_condition = [];
                    $now_month_condition[] = ['user_sn','=',$user_sn]; // 当前会员
                    $now_month_condition[] = ['is_finance','=',1]; // 已经结算佣金
                    $now_month_condition[] = ['create_time','like',$value['now_month'].'%'];
                    $adv_back_money = $backMoneyModel->where($condition)->where([['act','=',1]])->sum('money');
                    $adv_reduce_money = $backMoneyModel->where($condition)->where([['act','=',11]])->sum('money');
                    $list[$key]['adv_back_money'] = sprintf('%.2f',$adv_back_money-$adv_reduce_money);
                    // $list[$key]['adv_back_money'] = sprintf('%.2f',$backMoneyModel->where($condition)->where([['act','=',1]])->sum('money'));
                    $agent_back_money = $backMoneyModel->where($condition)->where([['act','=','2']])->sum('money');
                    $avt_agent_back_money = $backMoneyModel->where($condition)->where([['act','=','3']])->sum('money');
                    $list[$key]['agent_back_money'] = sprintf('%.2f', ($agent_back_money+ $avt_agent_back_money));
                    if ($list[$key]['agent_back_money'] <= 0) {
                        $list[$key]['agent_back_money'] = sprintf('%.2f',0);
                    }
                    $list[$key]['bonus_back_money'] = sprintf('%.2f',$backMoneyModel->where($now_month_condition)->where([['act','=',4]])->sum('money'));
                    $list[$key]['other_back_money'] = sprintf('%.2f',$backMoneyModel->where($condition)->where([['act','=',10]])->sum('money'));
                    $list[$key]['all_money'] =sprintf('%.2f', $list[$key]['adv_back_money']+$list[$key]['agent_back_money']+$list[$key]['bonus_back_money']+$list[$key]['other_back_money']);
                }
            }
            $resultData['list'] = $list;
            $result_code = 200;
            $result_msg = '加载成功';
        } catch (\Exception $e) {
            $result_code = 404;
            if ($e->getCode() == 203) {
                $result_code = 203;
            }
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }

    // +------------
    // | 海报背景
    // +--------------
    /**
     * @xk 海报背景列表
     *
     * @method getPosterList
     * @param  PosterModel   $posterModel               [description]
     * @return [type]        [description]
     * @Time   2021-10-20
     * @City   青岛
     * @Author xkyinzhe      <zhonghuaxinxing@sina.cn>
     */
    public function getPosterList(PosterModel $posterModel)
    {
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $page = isset($param['page']) ? (int)$param['page'] : 1;
            $limit = isset($param['limit']) ? (int)$param['limit'] : 30000;
            $condition = [];
            $result_count = $posterModel->where($condition)->count();
            if ($result_count <= ($page-1)*$limit) {
                $resultData['list'] = [];
                $resultData['page'] = $page;
                throw new \think\Exception("没有更多数据了", 203);
            }
            $condition[] = ['status','=',1];
            $result_code = 200;
            $result_msg = '请求成功';
            $resultData['list'] = $posterModel
                              ->where($condition)
                              ->field('`poster_id`,`poster_name`,`back_ground_picurl`')
                              ->withAttr('back_ground_picurl', function ($value, $data) {
                                  return getShowUrl($value);
                              })
                              ->page($page, $limit)
                              ->order('order_id desc')
                              ->select();
            $resultData['page'] = $page+1;
        } catch (\Exception $e) {
            $result_code = 404;
            if ($e->getCode() == '203') {
                $result_code = 203;
            }
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 推广海报详情
     *
     * @method getPosterInfo
     * @param  PosterModel   $posterModel               [description]
     * @param  UserModel     $userModel                 [description]
     * @return [type]        [description]
     * @Time   2021-10-20
     * @City   青岛
     * @Author xkyinzhe      <zhonghuaxinxing@sina.cn>
     */
    public function getPosterInfo(PosterModel $posterModel, UserModel $userModel, OSS $ossServices)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            $poster_id = isset($param['poster_id']) ? $param['poster_id'] : 0;
            // 判断用户是否具备生成推广码的条件
            $user_info = $userModel->where([['user_sn','=',$user_sn]])->field('`user_sn`,`level`,`is_bind`')->find();
            if (!$user_info) {
                throw new \think\Exception("您还没有登录，请先进行登录", 201);
            }
            if ($user_info['level'] <= 1) {
                throw new \think\Exception("您当前会员等级不允许生成推广海报", 201);
            }
            // 开始获取海报信息
            $poster_info = $posterModel->field('`poster_id`,`show_postion`,`back_ground_picurl`')->find($poster_id);
            if (!$poster_info) {
                throw new \think\Exception("海报背景不存在，请重试", 404);
            }
            $show_postion = $poster_info['show_postion'];
            // 开始生成会员二维码
            $user_ewm = $userModel->getUserEwm($user_sn, $poster_info);
            // 如果是OSS上传
            $upload_type = config('system_config.upload_type'); // 上传方式
            if ($upload_type == 1) {
                // oss上传方式
               $ossServices->fileUpload($user_ewm, $user_ewm); // 把生成的图片上传至oss
            }

            $whiteBG = getShowUrl($poster_info['back_ground_picurl']); // 获取推广二维码背景
            $url = $whiteBG.'?x-oss-process=image';
            switch ($show_postion) {
              case '1':
                $url .= '/watermark,image_'.urlsafe_b64encode($user_ewm.'?x-oss-process=image/resize,h_150,w_150,limit_0').',g_nw,x_50,y_80';//将文章图片添加到背景图上
                $url .= ossprocessTitle($user_info['user_sn'], 40, 250, 36, 'ad0d10', 'g_nw');//将文章图片添加到背景图上
                break;
              case '2':
                $url .= '/watermark,image_'.urlsafe_b64encode($user_ewm.'?x-oss-process=image/resize,h_150,h_150,limit_0').',g_ne,x_50,y_80';//将文章图片添加到背景图上
                $url .= ossprocessTitle($user_info['user_sn'], 40, 250, 36, 'ad0d10', 'g_ne');//将文章图片添加到背景图上
                break;
              case '3':
                $url .= '/watermark,image_'.urlsafe_b64encode($user_ewm.'?x-oss-process=image/resize,h_150,h_150,limit_0').',g_west,x_50';//将文章图片添加到背景图上
                $url .= ossprocessTitle($user_info['user_sn'], 40, 100, 36, 'ad0d10', 'g_west', -120);//将文章图片添加到背景图上
                break;
              case '4':
                $url .= '/watermark,image_'.urlsafe_b64encode($user_ewm.'?x-oss-process=image/resize,h_150,h_150,limit_0').',g_east,x_50';//将文章图片添加到背景图上
                $url .= ossprocessTitle($user_info['user_sn'], 40, 100, 36, 'ad0d10', 'g_east', -120);//将文章图片添加到背景图上
                break;
              case '5':
                $url .= '/watermark,image_'.urlsafe_b64encode($user_ewm.'?x-oss-process=image/resize,h_150,h_150,limit_0').',g_sw,x_50,y_80';//将文章图片添加到背景图上
                $url .= ossprocessTitle($user_info['user_sn'], 40, 30, 36, 'ad0d10', 'g_sw');//将文章图片添加到背景图上
                break;
              case '6':
                $url .= '/watermark,image_'.urlsafe_b64encode($user_ewm.'?x-oss-process=image/resize,h_150,h_150,limit_0').',g_se,x_50,y_80';//将文章图片添加到背景图上
                $url .= ossprocessTitle($user_info['user_sn'], 40, 30, 36, 'ad0d10', 'g_se');//将文章图片添加到背景图上
                break;
            }


            // $url .= ossprocessTitle($user_info['user_name'], 40, 230, 30, '333333', 'g_north');//将文章图片添加到背景图上
            // $url .= ossprocessTitle('-我的邀请码-', 40, 280, 20, '666666', 'g_north');
            // $url .= ossprocessTitle($user_info['user_sn'], 40, 330, 48, 'f86b1d', 'g_north');









            // 开始执行海报生成
            // $poster_pic = $this->createEwm($user_sn, $user_ewm, $show_postion, $poster_id, $back_ground_picurl);
            // echo $poster_pic; die();
            //   $result_code = 200;
            // $result_msg = '加载成功';
            $resultData['show_ewm_pic'] = $url;
            // $resultData = [];
            // $resultData['user_ewm'] = getShowUrl('/'.$poster_pic);
            // $resultData['show_postion'] = $poster_info['show_postion'];
            // $resultData['back_ground_picurl'] = getShowUrl($poster_info['back_ground_picurl']);
            $result_code = 200;
            $result_msg = '加载成功';
        } catch (\Exception $e) {
            $result_code = 404;
            if ($e->getCode() == 201) {
                $resultData['show_ewm_pic'] = '';
                $result_code = 200;
            }
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 执行二维码的合成获取
     *
     * @method createEwm
     * @param  [type]     $user_sn                   [description]
     * @param  [type]     $user_ewm                  [description]
     * @param  [type]     $show_postion              [description]
     * @param  [type]     $back_ground_picurl        [description]
     * @return [type]     [description]
     * @Time   2021-10-20
     * @City   青岛
     * @Author xkyinzhe   <zhonghuaxinxing@sina.cn>
     */
    public static function createEwm($user_sn, $user_ewm, $show_postion, $poster_id, $back_ground_picurl)
    {
        $path = 'upload/Qrcode/'.$user_sn; // 每个用户单独一个文件夹 用来存放当前用户的海报
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }
        $filename = $path.'/qc_'.$user_sn.'_'.$poster_id.'_'.$show_postion.'.png';
        // echo $filename; die();
        //第一步 整合背景图和海报图
        if ($back_ground_picurl&&$user_ewm) {
            $qrcode = imagecreatefromstring(file_get_contents($user_ewm));
            $background = imagecreatefromstring(file_get_contents('./'.$back_ground_picurl));
            $background_width = imagesx($background); //获取背景图宽度
             $background_height = imagesy($background); //获取背景图高度
             $header_width = imagesx($qrcode);
            $header_height = imagesy($qrcode);
            $last_height = $header_height*$background_width/$header_width;
            $image = \think\Image::open($user_ewm);
            // 按照原图的比例生成一个最大为200*200的缩略图并替换原来的图片(保存在原来的路径,文件名相同会被替换)
            $image->thumb(160, 160)->save($user_ewm);
            $font = 'static/common/font/NotoSansHans-Bold.otf';
            $black = imagecolorallocate($background, 0, 0, 0);
            $fontSize = 16;
            $point = 21;// gd2单位为磅，不是像素
            $charset = 'utf-8';
            switch ($show_postion) {
               case '1':
                 imagecopymerge($background, $qrcode, 10, 10, 0, 0, 105, 135, 100);
                 imagefttext($background, 16, 0, 18, 135, $black, $font, $user_sn);
                 break;
               case '2':
                 imagecopymerge($background, $qrcode, $background_width-115, 10, 0, 0, 105, 135, 100);
                 imagefttext($background, 16, 0, $background_width-108, 135, $black, $font, $user_sn);
                 break;
               case '3':
                 imagecopymerge($background, $qrcode, 10, 400, 0, 0, 105, 135, 100);
                 imagefttext($background, 16, 0, 18, 525, $black, $font, $user_sn);
                 break;
               case '4':
                 imagecopymerge($background, $qrcode, $background_width-115, 400, 0, 0, 105, 135, 100);
                 imagefttext($background, 16, 0, $background_width-108, 525, $black, $font, $user_sn);
                 break;
               case '5':
                 imagecopymerge($background, $qrcode, 20, $background_height-145, 0, 0, 105, 135, 100);
                 imagefttext($background, 16, 0, 28, $background_height-20, $black, $font, $user_sn);
                 break;
               case '6':
                 imagecopymerge($background, $qrcode, $background_width-115, $background_height-145, 0, 0, 105, 135, 100);
                 imagefttext($background, 16, 0, $background_width-108, $background_height-20, $black, $font, $user_sn);
                 break;
             }
            header("Content-type: image/png");
            imagepng($background, $filename);//根据需要生成相应的图片
            imagedestroy($background);
            imagedestroy($qrcode);
        }
        return '/'.$filename;
    }
    /**
     * @xk 余额转增记录保存
     *
     * @method moneyChanageSave
     * @param  UserModel         $userModel                 [description]
     * @param  MoneyChanageModel $moneyChanageModel         [description]
     * @return [type]            [description]
     * @Time   2021-10-29
     * @City   青岛
     * @Author xkyinzhe          <zhonghuaxinxing@sina.cn>
     */
    public function moneyChanageSave(UserModel $userModel, MoneyChanageModel $moneyChanageModel, Lock $lock, UserServices $userServices)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            // $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            $user_sn = isset($param['create_user_sn']) ? $param['create_user_sn'] : '';
            $push_user_sn = isset($param['push_user_sn']) ? $param['push_user_sn'] : '';
            $money = isset($param['money']) ? $param['money'] : 0.00;
            $user_name = isset($param['user_name']) ? $param['user_name'] : '';
            $lock = (new Lock())->lock([$push_user_sn,$user_sn], 6000);
            if (!$lock) {
                throw new \think\Exception("提交过于频繁，请稍后重试", 404);
            }
            $push_user_info = $userModel->where([['user_sn','=',$push_user_sn]])->field('`user_sn`,`back_money`,`user_name`')->find();
            $user_info = $userModel->where([['user_sn','=',$user_sn]])->field('`user_sn`,`back_money`,`user_name`')->find();
            if (!$push_user_info) {
                throw new \think\Exception("转出用户信息不存在", 404);
            }
            if (!$user_info) {
                throw new \think\Exception("转入用户信息不存在", 404);
            }
            if ($user_info['user_name'] != $user_name) {
                throw new \think\Exception("转入用户信息异常，请重试", 404);
            }
            if ($push_user_info['back_money'] < $money) {
                throw new \think\Exception("转出金额大于当前可提现金额，请重新输入", 404);
            }
            if ($money < config('web_config.min_give_money')) {
                throw new \think\Exception("转出金额必须大于".config('web_config.min_give_money'), 404);
            }
            // 提交转增信息
            $money_charge_data = [];
            $money_charge_data['user_name'] =  $user_name; // 接收人昵称
            $money_charge_data['user_sn'] =  $user_sn; // 接收人
            $money_charge_data['push_user_name'] =  $push_user_info['user_name']; // 转出人昵称
            $money_charge_data['push_user_sn'] =  $push_user_sn; // 转出人账号
            $money_charge_data['money'] =  $money;
            $money_charge_data['chanage_money'] =  $push_user_info['back_money'];
            $money_charge_data['status'] =  0; // 0=待审核 1=审核通过 2=审核失败
            // 余额转出提交
            $res = $moneyChanageModel->create($money_charge_data);
            // 扣除转增余额
            $userModel->where([['user_sn','=',$push_user_sn]])->dec('back_money', (float)$money)->update();
            // 将转增金额划入冻结
            $userModel->where([['user_sn','=',$push_user_sn]])->inc('frozen_money', (float)$money)->update();
            // 生成冻结金额
            $userModel->where([['user_sn','=',$user_sn]])->inc('frozen_money', (float)$money)->update();
            $content = '转出成功';
            $userServices->syncBalanceFinance((string)$res->money_chanage_id, 1, $content);
            Db::commit();
            $result_code = 200;
            $result_msg = '余额转赠成功，可在转赠记录查看详情';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 余额转入转出操作记录
     *
     * @method getMoneyChanageLog
     * @param  MoneyChanageModel  $moneyChanageModel         [description]
     * @return [type]             [description]
     * @Time   2021-10-29
     * @City   青岛
     * @Author xkyinzhe           <zhonghuaxinxing@sina.cn>
     */
    public function getMoneyChanageLog(MoneyChanageModel $moneyChanageModel)
    {
        $param = request()->param();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            $type = isset($param['type']) ? $param['type'] : '';
            $page = isset($param['page']) ? $param['page'] : 1;
            $limit = isset($param['limit']) ? $param['limit'] : 30;
            $condition = [];
            switch ($type) {
              case '1':
                $condition[] = ['push_user_sn','=',$user_sn];
                break;
              case '2':
                $condition[] = ['user_sn','=',$user_sn];
                break;
            }
            $result_count = $moneyChanageModel->where($condition)->count();
            if ($result_count <= ($page-1)*$limit) {
                $resultData['list'] = [];
                $resultData['page'] = $page;
                throw new \think\Exception("没有更多数据了", 203);
            }
            $resultData['list'] = $moneyChanageModel
                                  ->where($condition)
                                  ->field('`money_chanage_id`,`push_user_sn`,`user_sn`,`user_name`,`push_user_name`,`money`,`create_time`,`status`')
                                  ->page($page, $limit)
                                  ->order('create_time desc')
                                  ->select()
                                  ->toArray();
            $resultData['page'] = $page+1;
            $result_code = 200;
            $result_msg = '加载成功';
        } catch (\Exception $e) {
            $result_code = 404;
            if ($e->getCode() == 203) {
                $result_code = $e->getCode();
            }
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    // +----------------
    // | 我的搜索
    // +-------------------

    /**
     * @xk 历史搜索记录
     *
     * @method getHistorySearch
     *
     * @param HistorySearchModel $historySearchModel [description]
     * @param UserModel          $userModel          [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-13T14:39:11+080
     */
    public function getHistorySearch(HistorySearchModel $historySearchModel, UserModel $userModel)
    {
        $param = request()->param();
        $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
        $condition = [];
        $condition[] = ['user_sn', '=', $user_sn];
        $list = $historySearchModel
            ->where($condition)
            ->distinct(true)
            ->column('keywords');
        $code = 200;
        $msg = '请求成功';
        $result_code = 200;
        $result_msg = '加载成功';
        $resultData = [];
        $resultData['list'] = $list;
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }

    /**
     * @xk 清除历史搜索记录
     *
     * @method clearHistorySearch
     *
     * @param HistorySearchModel $historySearchModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-13T14:50:25+080
     */
    public function clearHistorySearch(HistorySearchModel $historySearchModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            $res = $historySearchModel->destroy(function ($query) use ($user_sn) {
                $query->where([['user_sn', '=', $user_sn]]);
            });
            Db::commit();
            $result_code = 200;
            $result_msg = '清除成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }
    /**
     * @xk 执行认证信息提交和保存
     *
     * @method saveCheck
     * @param  Huigongbao $huigongbao                [description]
     * @return [type]     [description]
     * @Time   2021-11-05
     * @City   青岛
     * @Author xkyinzhe   <zhonghuaxinxing@sina.cn>
     */
    public function saveCheck(Huigongbao $huigongbao, UserModel $userModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        // php 截取字符串
        try {
            $param = request()->param();
            // 开始组合惠工宝的相关资料信息
            $huigong_data = [];
            $huigong_data['name'] = $param['name'];
            $huigong_data['idCardNumber'] = $param['card_num'];
            $huigong_data['image1'] = '';
            $huigong_data['image2'] = '';
            $huigong_data['imageUrl1'] = getShowUrl($param['card_pic']);
            $huigong_data['imageUrl2'] = getShowUrl($param['card_pic_back']);
            $huigong_data['bankNumber'] = $param['bank_card_num'];
            $huigong_data['bankName'] = $param['bank_name'];
            $huigong_data['bankAddress'] = '';
            $huigong_data['phone'] = $param['tel'];
            $card_num = $huigongbao->createUser($huigong_data);
            if ($card_num) {
                $userModel->where([['user_sn','=',$param['user_sn']]])->save(['card_num'=>$card_num,'is_check'=>1]);
            }
            Db::commit();
            $result_code = 200;
            $result_msg = '实名认证信息提交成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 获取银行信息
     *
     * @method getBankInfo
     * @param  Huigongbao  $huigongbao                [description]
     * @return [type]      [description]
     * @Time   2021-11-10
     * @City   青岛
     * @Author xkyinzhe    <zhonghuaxinxing@sina.cn>
     */
    public function getBankInfo(Huigongbao $huigongbao)
    {
        mb_internal_encoding("UTF-8");
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        $param = request()->param();
        $card_num = isset($param['card_num']) ? $param['card_num'] : '';
        $type = isset($param['type']) ? $param['type'] : '';
        $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
        $act = isset($param['act'])?$param['act']:'nomal';
        try {
            if ($card_num == '') {
                throw new \think\Exception("请检查是否完善过信息", 404);
            }
            if ($type == 'withDrawal') {
                // 提现的各种要求条件
                $now_day = date("w");
                if ($now_day != 5) {
                    throw new \think\Exception("每周五开放提现功能。遇到节假日，提现审核会顺延至节后哦！", 404);
                }
            }
            $info = $huigongbao->getBankInfo(trim($card_num));

            if($type != 'withDrawal'){
                $info['show_bankAccount'] = substr_replace($info['account'],'*************',3,9);
                // $info['show_bankAccount'] = $info['account'];
                $info['show_idCard'] = substr_replace($info['idCard'],'*************',3,11);
                $info['show_name'] = '*'.mb_substr($info['name'],1,2,'utf-8');
            }
            $info['bankName'] = $info['depositBank']; // 开户行
            $info['bankAccount'] = $info['account']; // 开户行
            $info['is_show'] = 1;
            $info['min_money'] = (float)config('web_config.min_withdrawl_money');
            $info['hgb_status'] = config('web_config.hgb_status'); // 惠工宝合规资料修改
            if ($info['hgb_status'] == 1) {
                $hg_appid = config('core_config.huigongbao_new_config.hg_appid');
                $callBackUrl = urlencode('https://'.$_SERVER['HTTP_HOST'].'/#/pages/administration/administration');
                $checkUrl = config('core_config.huigongbao_new_config.hg_jumpurl').'appId='.$hg_appid.'&callBackUrl='.$callBackUrl.'&remark='.$user_sn;
                $info['checkUrl'] = $checkUrl;
            }
            $resultData[] = $info;
            $result_code = 200;
            $result_msg = '加载成功';
        } catch (\Exception $e) {
            $result_code = 404;
            if ($e->getCode() == 300) {
                if ($type != 'withDrawal') {
                    $resultData['type'] = "_black";
                }
                $result_code = 300;
            }
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    //判断是否
    public function isPUser(){
        $code = 200;
        $msg = '请求成功';
        $result_code=200;
        $result_msg="请求成功";
        $resultData['type']=config("web_config.is_p_user");
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    public function delUser(){
        $code = 200;
        $msg = '请求成功';
        $result_code=200;
        $result_msg="请求成功";
        $param = request()->param();
        $where_find['user_sn']=$param['user_sn'];
        DB::name('user')->where($where_find)->delete();
        $this->result($code, $msg, $result_code, $result_msg);
    }
    //获取上级用户信息
    public function changesLUserinfo(UserModel $userModel){
        $code = 200;
        $msg = '请求成功';
        $data['state']=1;
        $param = request()->param();
        $l_user_sn = isset($param['l_user_sn']) ? $param['l_user_sn'] : '';
        $user_find = $userModel->where([['user_sn','=',$l_user_sn]])->field('user_sn,user_name,head_pic,level')->find();//获取用户创建时间 30天内才可以更改
        
        if(empty($user_find)){
            $result_code=203;
            $msg="会员号有误,请重新填写";
        
        }else{
           $data['user_sn']=$user_find['user_sn'];
        $data['user_name']=$user_find['user_name'];
        $data['head_pic']=$user_find['head_pic'];
        $result_code=200;
        $msg="请求成功";
        // if($user_find['level']<=1){
        //   $result_code=203; 
        //   $msg="分享人绑定失败，请重试";
        // } 
        }
        
        $this->result($code, $msg, $result_code,$msg,$data);
     }
    /**
     * 判断是否可以更改上下级
     */
     public function ischangesLUserSn(UserModel $userModel){
        $code = 200;
        $msg = '请求成功';
        $data['state']=1;
        $param = request()->param();
        $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
        $user_find = $userModel->where([['user_sn','=',$user_sn]])->field('create_time,level')->find();//获取用户创建时间 // 30天内才可以更改
        // dump($user_find);die;
        if(time()>strtotime('+30 days', strtotime($user_find['create_time']))){
            $data['state']=0;
        }else{//时间条件满足了 判断是否身份也满足
            if($user_find['level']!=1){
                $data['state']=0;
            }
        }
        $result_code = 200;
        $this->result($code, $msg, $result_code,"请求成功",$data);
     }
    /**
     * @xk 动态换绑上级
     *
     * @method chanageLUserSn
     * @param  UserModel      $userModel                 [description]
     * @param  UserServices   $userServices              [description]
     * @return [type]         [description]
     * @Time   2021-11-11
     * @City   青岛
     * @Author xkyinzhe       <zhonghuaxinxing@sina.cn>
     */
    public function chanageLUserSn(UserModel $userModel, UserServices $userServices)
    {
        // die("asd");
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $param = request()->param();
        $l_user_sn = isset($param['l_user_sn']) ? base64_decode($param['l_user_sn']) : '';
        // $l_user_snse = $param['l_user_sn'];
        // var_dump($l_user_snse);die;
        $user_find = $userModel->where([['user_sn','=',$l_user_sn]])->field('level')->find();//获取用户创建时间 //
        // var_dump($user_find);die;
        if(empty($user_find)){
            $result_code=203; 
          $msg="没有此用户";
          $this->result($code, $msg, $result_code,$msg,"");
          return "";
        }else{
          if($user_find['level']<=1){
           $result_code=203; 
           $msg="分享人绑定失败，请重试";
           $this->result($code, $msg, $result_code,$msg,"");
           return "";
        }  
        }
        
        try {
            
            // dump($param);die;
            
            $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            
            $is_all_bind = $userModel->where([['user_sn','=',$user_sn]])->value('is_all_bind');
            $user_time = $userModel->where([['user_sn','=',$user_sn]])->value('create_time');//获取用户创建时间 // 30天内才可以更改
            // var_dump($user_time);die;
            if(time()>strtotime('+30 days', strtotime($user_time))){
                 throw new \think\Exception("您好,您已超过30天不可更改", 404);
            }
            
            $check_now_time = checkNowTime();
            if ($is_all_bind == 0 && $check_now_time == 1) {
               
                $userServices->syncChanageUser($user_sn, $l_user_sn);
            }
            Db::commit();
            $result_code = 200;
            $result_msg = '换绑成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 203;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg,'');
    }
    /**
     * @xk 校验用户是否实名认证过
     *
     * @method checkCardNum
     * @param  Huigongbao   $huigongbao                [description]
     * @return [type]       [description]
     * @Time   2021-12-02
     * @City   青岛
     * @Author xkyinzhe     <zhonghuaxinxing@sina.cn>
     */
    public function checkCardNum(UserModel $userModel, Huigongbao $huigongbao)
    {
        $param = request()->param();
        $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
        $card_num = isset($param['card_num']) ? $param['card_num'] : '';
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            if ($user_sn == '') {
                throw new \think\Exception("您还没有登录，请先进行登录", 404);
            }
            if ($card_num == '') {
                throw new \think\Exception("请输入正确的身份证号码", 404);
            }
            $checkResult = $userModel->validate($param, 'cardNum');
            $user_info = $userModel
                   ->alias('u')
                   ->where([['u.user_sn', '=', $user_sn]])
                   ->field('u.`user_sn`,u.`card_num`,u.`is_check`')
                   ->find();
            if (!$user_info) {
                throw new \think\Exception("用户信息不存在，请仔细检查", 404);
            }
            $user_info->toArray();

            $count = $userModel->where([['card_num','=',$param['card_num']]])->count();
            if ($count > 0) {
                throw new \think\Exception("身份证已经绑定过了，请不要重复绑定", 404);
            }
            $res = $huigongbao->checkCardNum($param['card_num']);
            if ($res === 'true') {
                $resultData['type'] = 1;
            } else {
                $hg_appid = config('core_config.huigongbao_new_config.hg_appid');
                $callBackUrl = urlencode('https://'.$_SERVER['HTTP_HOST'].'/#/pages/administration/administration');
                $checkUrl = config('core_config.huigongbao_new_config.hg_jumpurl').'appId='.$hg_appid.'&callBackUrl='.$callBackUrl.'&remark='.$user_sn;
                $resultData['checkUrl'] = $checkUrl;
                $resultData['type'] = 2;
            }
            $result_code = 200;
            $result_msg = '校验成功';
        } catch (\Exception $e) {
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 修改银行卡信息
     *
     * @method chanageBankSave
     * @param  UserModel       $userModel                 [description]
     * @param  Huigongbao      $huigongbao                [description]
     * @return [type]          [description]
     * @Time   2021-12-02
     * @City   青岛
     * @Author xkyinzhe        <zhonghuaxinxing@sina.cn>
     */
    public function chanageBankSave(UserModel $userModel, Huigongbao $huigongbao)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        // php 截取字符串
        try {
            $param = request()->param();
            $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            $user_info = $userModel
                 ->alias('u')
                 ->where([['u.user_sn', '=', $user_sn]])
                 ->field('u.`user_sn`,u.`card_num`,u.`is_check`')
                 ->find();
            if (!$user_info) {
                throw new \think\Exception("用户信息不存在，请仔细检查", 404);
            }
            if ($user_info['is_check'] == 0) {
                throw new \think\Exception("账户还没有进行过实名认证", 404);
            }
            $user_info->toArray();
            // // 开始组合惠工宝的相关资料信息
            // $huigong_data = [];
            // $huigong_data['idCardNumber'] = $user_info['card_num'];
            // $huigong_data['bankNumber'] = $param['bank_card_num'];
            // $huigong_data['bankName'] = $param['bank_name'];
            // $huigong_data['name'] = $param['name'];
            // // 执行校验
            // $userModel->validate($huigong_data,'chanageBank');
            // $card_num = $huigongbao->chanageBank($huigong_data);
             // 开始组合惠工宝的相关资料信息
             $huigong_data = [];
             $huigong_data['idCard'] = $user_info['card_num'];
             $huigong_data['account'] = trim($param['bank_card_num']);
             // $huigong_data['bankName'] = $param['bank_name'];
             $huigong_data['name'] = $param['name'];
             $huigong_data['type'] = 10;
             $huigong_data['phone'] = $user_info['tel'];
             // 执行校验
             $userModel->validate($huigong_data,'chanageBank');
             $huigongbao->chanageBank($huigong_data);
            Db::commit();
            $result_code = 200;
            $result_msg = '银行信息提交成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 获取代理订单
     * @method                                      getVipOrder
     * @param                                       UserModel $userModel  [description]
     * @param                                       BackMoneyModel $backMoneyModel  [description]
     * @return                                      [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                             <zhonghuaxinxing@sina.cn>
     * @City：                                       青岛
     * @Time：2022-02-28Tfalse11:false35:false11+080
     */
    public function getVipOrder(UserModel $userModel, BackMoneyModel $backMoneyModel, GoodsOrderModel $goodsOrderModel)
    {
        $param = request()->param();
        $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
        $type = isset($param['type']) ? $param['type'] : 'waitSure';
        $limit = isset($param['limit']) ? (int)$param['limit'] : 50;
        $page = isset($param['page']) ? (int)$param['page'] : 1;
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            if ($user_sn == '') {
                throw new \think\Exception("您还没有登录，请先进行登录", 404);
            }
            $condition = [];
            $condition[] = ['back.user_sn','in',$user_sn];
            $new_list = [];
            switch ($type) {
              case 'waitSure':
                $condition[] = ['back.act','=','1'];
                $condition[] = ['back.is_finance','=',0];
                $list = $backMoneyModel
                        ->alias('back')
                        ->leftJoin('user u', 'u.user_sn=back.create_user_sn')
                        ->where($condition)
                        ->field('back.`act`,back.`back_money_id`,back.`money`,back.`sub_order_sn`,back.`achievement_price`,back.`create_time`,back.`create_user_sn` as user_sn,u.`user_name`')
                        ->page($page, $limit)
                        ->order(['create_time desc'])
                        ->select()
                        ->toArray();
                  if ($list) {
                      foreach ($list as $key => $value) {
                          $search_condition = [['sub_order_sn','=',$value['sub_order_sn']],['act','=','11']];
                          $all_money = $backMoneyModel->where($search_condition)->sum('money');
                          $goods_condition = [];
                          $goods_condition[] = ['sub_order_sn','=',$value['sub_order_sn']];
                          $goods_condition[] = ['status','in','1.1,2.1,5.1,5.11,5.12,5.21,5.22,5.23,5.24,5.31,5.32,5.33,5.34'];
                          // 此处获取全部 已付款 待确认的商品金额
                          $all_buy_money = $goodsOrderModel->where($goods_condition)->sum('sub_total');
                          $value['money'] = sprintf('%.2f',((float)$value['money']-(float)$all_money));
                          $value['achievement_price'] = $all_buy_money;
                          if ($all_buy_money > 0) {
                              $new_list[] = $value;
                          }
                      }
                  }
                break;
              case 'sure':
                $condition[] = ['act','=',1];
                $condition[] = ['is_finance','=',1];
                $list = $backMoneyModel
                        ->alias('back')
                        ->leftJoin('user u', 'u.user_sn=back.create_user_sn')
                        ->where($condition)
                        ->field('back.`act`,back.`back_money_id`,back.`money`,back.`sub_order_sn`,back.`achievement_price`,back.`create_time`,back.`create_user_sn` as user_sn,u.`user_name`')
                        ->page($page, $limit)
                        ->order(['create_time desc'])
                        ->select()
                        ->toArray();
                  if ($list) {
                      foreach ($list as $key => $value) {
                          $search_condition = [['sub_order_sn','=',$value['sub_order_sn']],['act','=','11']];
                          $all_money = $backMoneyModel->where($search_condition)->sum('money');
                          $goods_condition = [];
                          $goods_condition[] = ['sub_order_sn','=',$value['sub_order_sn']];
                          $goods_condition[] = ['status','=','3.1'];
                          // 此处获取全部 已付款 待确认的商品金额
                          $all_buy_money = $goodsOrderModel->where($goods_condition)->sum('sub_total');
                          $value['money'] = sprintf('%.2f',((float)$value['money']-(float)$all_money));
                          $value['achievement_price'] = $all_buy_money;
                          if ($all_buy_money > 0) {
                              $new_list[] = $value;
                          }
                      }
                  }
                break;
              case 'refund':
                $condition[] = ['act','=',11];
                $list = $backMoneyModel
                        ->alias('back')
                        ->leftJoin('user u', 'u.user_sn=back.create_user_sn')
                        ->where($condition)
                        ->field('back.`act`,back.`back_money_id`,back.`money`,back.`sub_order_sn`,back.`achievement_price`,back.`create_time`,back.`create_user_sn` as user_sn,u.`user_name`,sum(back.`money`) as money')
                        ->page($page, $limit)
                        ->order(['create_time desc'])
                        ->group('sub_order_sn')
                        ->select()
                        ->toArray();
                        if ($list) {
                            foreach ($list as $key => $value) {
                                $goods_condition = [];
                                $goods_condition[] = ['sub_order_sn','=',$value['sub_order_sn']];
                                $goods_condition[] = ['status','in','5.13,5.25'];
                                // 此处获取全部 已付款 待确认的商品金额
                                $all_buy_money = $goodsOrderModel->where($goods_condition)->sum('sub_total');
                                $value['achievement_price'] = sprintf('%.2f',(float)$all_buy_money);
                                if ($all_buy_money > 0) {
                                    $new_list[] = $value;
                                }
                            }
                        }
                break;
            }
            $result_count = $backMoneyModel->alias('back')->where($condition)->count();
            $result_code = 200;
            $result_msg = '加载成功';
            $resultData['list'] = $new_list;
            $resultData['count'] = $result_count;
        } catch (\Exception $e) {
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 账号注销
     * @method                                      deleteUserSn
     * @param                                       UserModel $userModel  [description]
     * @param                                       UserServices $userServices  [description]
     * @return                                      [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                             <zhonghuaxinxing@sina.cn>
     * @City：青岛
     * @Time：2022-06-20Tfalse10:false23:false48+080
     */
    public function deleteUserSn(UserModel $userModel,GoodsOrderModel $goodsOrderModel,UserServices $userServices){
      $result_code = 200;
      $result_msg = '账户注销成功，正在返回登录页面';
      Db::startTrans();
      try {
        $param = request()->param();
        $user_sn = isset($param['user_sn'])?$param['user_sn']:'';
        // $goods_order_count = $goodsOrderModel
        //                       ->where([['status','in','1.1,2.1,5.1,5.12,5.11,5.2,5.22,5.21,5.23,5.24,5.3,5.31,5.32,5.33,5.34']])
        //                       ->count();
        // if($goods_order_count > 0){
        //   throw new \think\Exception("当前还存在未完成订单，不允许注销", 404);
        // }
        $res = $userModel
              ->where([['user_sn', '=', $param['user_sn']]])
              ->find()
              ->save(['status' => '0']);
        Db::commit();
      } catch (\Exception $e) {
        $result_code = $e->getCode();
        $result_msg = $e->getMessage();
        Db::rollback();
      }
      $this->result(200,'请求成功',$result_code,$result_msg);
    }
}
